package com.yixun.qfbao.api.service.impl;

import com.yixun.qfbao.api.service.CompanyService;
import com.yixun.qfbao.apidto.*;
import com.yixun.qfbao.mapper.CompanyMapper;
import com.yixun.qfbao.mapper.CompanyRelationMapper;
import com.yixun.qfbao.mapper.DepartmentMapper;
import com.yixun.qfbao.model.Company;
import com.yixun.qfbao.model.CompanyRelation;
import com.yixun.qfbao.model.Department;
import com.yixun.qfbao.model.dto.CompanyDto;
import com.yixun.qfbao.model.dto.CompanyRelationDto;
import com.yixun.qfbao.model.dto.DepartmentDto;
import com.yixun.qfbao.model.enums.DelFlagEnum;
import com.yixun.qfbao.model.enums.SystemIdEnum;
import com.yixun.qfbao.xf.model.Premises;
import com.yixun.qfbao.xf.model.dto.PremisesDto;
import com.yixun.qfbao.xf.model.enums.CheckSwitchEnum;
import com.yixun.qfbao.xf.model.enums.FreeAuditEnum;
import com.yixun.qfbao.xf.model.enums.ResultEnum;
import com.yixun.qfbao.xf.service.PremisesService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author guifang.weng
 * @create 2017-11-27 10:28
 **/
@Service
public class CompanyServiceImpl implements CompanyService {
	
	@Autowired
	private CompanyMapper companyMapper;
	@Autowired
	private CompanyRelationMapper companyRelationMapper;
	@Autowired
	private DepartmentMapper departmentMapper;
	@Autowired
    private PremisesService premisesService;
	
	@Override
	public Company getCompanyById(Long id) {
		return companyMapper.selectById(id);
	}
	
	@Override
	public boolean getCommissionFlag(Long higherId) {
		Company company = companyMapper.selectById(higherId);
		boolean flag = true;
		if ("0".equals(company.getCommissionFlag())) {
			flag = false;
		}
		return flag;
		
	}
	
	@Override
	public GetCompanyByPhoneResDto getCompanyByPhone(GetCompanyByPhoneReqDto entity) {
		GetCompanyByPhoneResDto resDto = new GetCompanyByPhoneResDto();
		CompanyDto companyDto = new CompanyDto();
		companyDto.setPhone(entity.getPhone());
		List<Company> list = companyMapper.getCompanyByPhone(companyDto);
		resDto.setCompanyList(list);
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}
	
	@Override
	public GetCompanyByPhoneResDto getCompanyByAssistantPhone(GetCompanyByPhoneReqDto entity) {
		GetCompanyByPhoneResDto resDto = new GetCompanyByPhoneResDto();
		CompanyDto companyDto = new CompanyDto();
		companyDto.setPhone(entity.getPhone());
		List<Company> list = companyMapper.getCompanyByAssistantPhone(companyDto);
		resDto.setCompanyList(list);
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		return resDto;
	}

	@Override
	public Company selectByDto(CompanyDto entity) {
		return companyMapper.selectByDto(entity);
	}

	@Override
	public ChangeAgencyIndexSwitchResDto changeAgencyIndexSwitch(ChangeAgencyIndexSwitchReqDto reqDto) {
		ChangeAgencyIndexSwitchResDto resDto = new ChangeAgencyIndexSwitchResDto();

        CompanyDto entity = new CompanyDto();
        if(StringUtils.isNotEmpty(reqDto.getCompanyUuid())){
            entity.setCompanyUuid(reqDto.getCompanyUuid());
        }else{
            entity.setDomain(reqDto.getDomain());
        }
        Company company = selectByDto(entity);
        if(null == company) {
            resDto.setResult(ResultEnum.FAIL.getNo());
            resDto.setResultMsg("未获取到公司信息！");
            return resDto;
        }
        if(StringUtils.isNotEmpty(reqDto.getAgencyIndexSwitch())){
            company.setAgencyIndexSwitch(reqDto.getAgencyIndexSwitch());
        }
        if(StringUtils.isNotEmpty(reqDto.getRepeatReportSwitch())) {
            company.setRepeatReportSwitch(reqDto.getRepeatReportSwitch());
        }
        // 不关闭,根据开启楼盘数量判断是否开启
//		if(StringUtils.isNotEmpty(reqDto.getCheckSwitch())) {
//			company.setCheckSwitch(reqDto.getCheckSwitch());
//		}
		companyMapper.edit(company);
		// 开启允许重复报备，则设置可重复报备楼盘
		if (reqDto.getRepeatReportSwitch() != null && "1".equals(reqDto.getRepeatReportSwitch())) {
            List<Long> premisesIdList = reqDto.getRepeatReportPremisesList();
            if (premisesIdList != null && premisesIdList.size() > 0) {
                // 全部置为 不可重复报备
                PremisesDto premisesDto = new PremisesDto();
                premisesDto.setCompanyId(company.getId());
                premisesService.updatePremisesForNoRepeatReport(premisesDto);
                // 设置已选择的楼盘设为可重复报备
                premisesService.updatePremisesForRepeatReport(premisesIdList);
            }
        }

		if (CheckSwitchEnum.OPEN.getNo().equals(reqDto.getCheckSwitch())) {
			// 开启短信验真，设置需要验真的报备楼盘
			List<Long> premisesIds = reqDto.getCheckSwitchPremisesList();
			if (premisesIds != null && premisesIds.size() > 0) {
				// 全部置为 不需要短信验真
				PremisesDto premisesDto = new PremisesDto();
				premisesDto.setCompanyId(company.getId());
				premisesService.updatePremisesForNoCheckSwitch(premisesDto);
				// 设置已选择的楼盘设为需要短信验真
				premisesService.updatePremisesForCheckSwitch(premisesIds);
			}
		}else if(CheckSwitchEnum.CLOSED.getNo().equals(reqDto.getCheckSwitch())){
			// 关闭短信验真,即关闭所有楼盘
			PremisesDto premisesDto = new PremisesDto();
			premisesDto.setCompanyId(company.getId());
			premisesService.updatePremisesForNoCheckSwitch(premisesDto);
		}

		// 开启短信验真，设置需要验真的报备楼盘
		if (FreeAuditEnum.FREE_REPORT_AUDIT.getNo().equals(reqDto.getFreeAudit())) {
			List<Long> premisesIds = reqDto.getFreeAuditPremisesList();
			if (premisesIds != null && premisesIds.size() > 0) {
				// 全部置为 不可重复报备
				PremisesDto premisesDto = new PremisesDto();
				premisesDto.setCompanyId(company.getId());
				premisesService.updatePremisesForNoFreeAudit(premisesDto);
				// 设置已选择的楼盘设为可重复报备
				premisesService.updatePremisesForFreeAudit(premisesIds);
			}
		}else if(FreeAuditEnum.NEED_AUDIT.getNo().equals(reqDto.getFreeAudit())){
			// 关闭短信验真,即关闭所有楼盘
			PremisesDto premisesDto = new PremisesDto();
			premisesDto.setCompanyId(company.getId());
			premisesService.updatePremisesForNoFreeAudit(premisesDto);
		}

		resDto.setResult(ResultEnum.SUCCESS.getNo());
		resDto.setResultMsg("操作成功");
		return resDto;
	}
	@Override
	public GetCompanyInfoResDto getCompanyInfo(GetCompanyInfoReqDto entity){
		GetCompanyInfoResDto getCompanyInfoResDto = new GetCompanyInfoResDto();
		Long devCompanyId = null;
		if(!SystemIdEnum.WEAPP_AGENCY.getCode().equals(entity.getLoginType())){
			//获取渠道商下是否存在该公司
			CompanyDto companyDto = new CompanyDto();
			companyDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			companyDto.setCompanyUuid(entity.getCompanyUuid());
			companyDto.setDomain(entity.getDomain());
			List<Company> devCompany = companyMapper.selectListByDto(companyDto);
			if(devCompany == null || devCompany.size() == 0){
				getCompanyInfoResDto.setResult(ResultEnum.FAIL.getNo());
				getCompanyInfoResDto.setResultMsg("渠道商不存在");
				return getCompanyInfoResDto;
			}
			devCompanyId = devCompany.get(0).getId();
		}

		//查询关联关系
		CompanyRelationDto companyRelationDto = new CompanyRelationDto();
		companyRelationDto.setDevCompany(devCompanyId);
		companyRelationDto.setAgentCompany(entity.getCompanyId());
		companyRelationDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		List<CompanyRelation> companyRelations = companyRelationMapper.selectListByDto(companyRelationDto);
		if(companyRelations == null || companyRelations.size() == 0){
			getCompanyInfoResDto.setResult(ResultEnum.FAIL.getNo());
			getCompanyInfoResDto.setResultMsg("该渠道商不存在此分销公司");
			return getCompanyInfoResDto;
		}

		Company company = companyMapper.selectById(entity.getCompanyId());
		if(null == company){
			getCompanyInfoResDto.setResult(ResultEnum.FAIL.getNo());
			getCompanyInfoResDto.setResultMsg("分销公司不存在");
			return getCompanyInfoResDto;
		}else{
			getCompanyInfoResDto.setCode(company.getCompanyCode());
			getCompanyInfoResDto.setCompanyId(company.getId());
			getCompanyInfoResDto.setCompanyName(company.getCompanyName());
			getCompanyInfoResDto.setResult(ResultEnum.SUCCESS.getNo());

			//获取门店列表
			getCompanyInfoResDto.setStoreList(getStoreList(company.getId()));
			if(entity.getStoreId() != null) {
				//获取组别信息
				getCompanyInfoResDto.setGroupList(getGroupList(entity.getStoreId()));
			}
			//获取组别信息
			return getCompanyInfoResDto;
		}
	}
	public List<Department> getStoreList(Long companyId){
		DepartmentDto departmentDto = new DepartmentDto();
		departmentDto.setMerchantId(companyId);
		departmentDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		departmentDto.setParentId(0L);
		List<Department> departmentMerchant = departmentMapper.selectListByDto(departmentDto);
		if(departmentMerchant ==null || departmentMerchant.size() == 0 ){
			return null;
		}
		departmentDto.setParentId(departmentMerchant.get(0).getId());
		//获取门店列表
		List<Department> storeList = departmentMapper.selectListByDto(departmentDto);
		return storeList;
	}
	public List<Department> getGroupList(Long storeId){
		DepartmentDto departmentDto = new DepartmentDto();
		departmentDto.setParentId(storeId);
		departmentDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		List<Department> list = departmentMapper.selectListByDto(departmentDto);
		return list;
	}

    @Override
    public GetAgencyIndexSwitchResDto getAgencyIndexSwitch(GetAgencyIndexSwitchReqDto reqDto) {
        GetAgencyIndexSwitchResDto resDto = new GetAgencyIndexSwitchResDto();
        if(StringUtils.isBlank(reqDto.getCompanyUuid())){
            resDto.setAgencyIndexSwitch("1");
            resDto.setRepeatReportSwitch("0");
            resDto.setCheckSwitch(CheckSwitchEnum.CLOSED.getNo());
            resDto.setCheckSwitchShow(Boolean.FALSE);
            resDto.setFreeAudit(FreeAuditEnum.NEED_AUDIT.getNo());
            return resDto;
        }
        CompanyDto entity = new CompanyDto();
        entity.setCompanyUuid(reqDto.getCompanyUuid());
        Company company = selectByDto(entity);
        String agencyIndexSwitch = StringUtils.isNotBlank(company.getAgencyIndexSwitch()) ? company.getAgencyIndexSwitch() : "1";
        String repeatReportSwitch = StringUtils.isNotBlank(company.getRepeatReportSwitch()) ? company.getRepeatReportSwitch() : "0";
		String checkSwitch = StringUtils.isNotBlank(company.getCheckSwitch()) ? company.getCheckSwitch() : CheckSwitchEnum.CLOSED.getNo();
		String companyName = company.getCompanyName();
		String companyAbbreviation = company.getCompanyAbbreviation();
		resDto.setCompanyName(companyName);
		resDto.setCompanyAbbreviation(companyAbbreviation);
		
		PremisesDto premisesDto = new PremisesDto();
		premisesDto.setCompanyId(company.getId());
		List<Premises> premisesList = premisesService.selectIdListByDto(premisesDto);

		List<Premises> repeatList = premisesList.stream().filter(item ->
			Objects.nonNull(item.getRepeatReportFlag()) && item.getRepeatReportFlag().intValue() == 1
		).collect(Collectors.toList());
		List<Premises> checkSwitchList = premisesList.stream().filter(item -> CheckSwitchEnum.OPEN.getNo().equals(item.getCheckSwitch())).collect(Collectors.toList());
		List<Premises> freeAuditList = premisesList.stream().filter(item -> FreeAuditEnum.FREE_REPORT_AUDIT.getNo().equals(item.getFreeAudit())).collect(Collectors.toList());

        List<Long> premisesIdList = null;
        if ("1".equals(repeatReportSwitch)) {
            if (repeatList != null && repeatList.size() > 0) {
                premisesIdList = repeatList.stream().map(premises -> premises.getId()).collect(Collectors.toList());
				resDto.setRepeatReportPremisesList(premisesIdList);
            }
        }

		resDto.setCheckSwitchShow(CheckSwitchEnum.CLOSED.getNo().equals(checkSwitch)?Boolean.FALSE:Boolean.TRUE);
		if (CollectionUtils.isNotEmpty(checkSwitchList)) {
			premisesIdList = checkSwitchList.stream().map(premises -> premises.getId()).collect(Collectors.toList());
			resDto.setCheckSwitchPremisesList(premisesIdList);
			checkSwitch = CheckSwitchEnum.OPEN.getNo();
		}else{
			checkSwitch = CheckSwitchEnum.CLOSED.getNo();
		}

		resDto.setFreeAudit(FreeAuditEnum.NEED_AUDIT.getNo());
		if (freeAuditList != null && freeAuditList.size() > 0) {
			premisesIdList = freeAuditList.stream().map(premises -> premises.getId()).collect(Collectors.toList());
			resDto.setFreeAuditPremisesList(premisesIdList);
			resDto.setFreeAudit(FreeAuditEnum.FREE_REPORT_AUDIT.getNo());
		}

        resDto.setAgencyIndexSwitch(agencyIndexSwitch);
        resDto.setRepeatReportSwitch(repeatReportSwitch);
        resDto.setCheckSwitch(checkSwitch);

        return resDto;
    }

    /*
     * 根据companyCode查询公司信息
     */
	@Override
	public Company selectCompanyByCompanyCode(String companyCode, Long companyId, List<String> companyUuids) {
		CompanyDto companyDto = new CompanyDto();
		companyDto.setCompanyCode(companyCode);
		companyDto.setId(companyId);
		companyDto.setCompanyUuids(companyUuids);
		return companyMapper.selectByAssitantCompanyUuids(companyDto);
	}

	@Override
	public int edit(Company company) {
		return companyMapper.edit(company);
	}
}
